package io.renren.system.sys.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.system.sys.dto.SysRegionDTO;
import io.renren.system.sys.entity.SysRegionEntity;
import io.renren.system.sys.enums.RegionHasChildareaEnum;
import io.renren.system.sys.service.SysRegionService;
import io.renren.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/region")
@Api(tags = "系统设置-地区管理")
public class SysRegionController {
    @Autowired
    private SysRegionService sysRegionService;

    @GetMapping("{id}")
    @ApiOperation("根据主键获取地区区域详细信息")
    @RequiresPermissions("sys:region:info")
    public Result<SysRegionDTO> get(@PathVariable("id") Long id) {
        SysRegionDTO data = sysRegionService.get(id);
        return new Result<SysRegionDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("新增保存地区区域信息")
    @LogOperation("新增保存地区区域信息")
    @RequiresPermissions("sys:region:save")
    public Result save(@RequestBody SysRegionDTO dto) {


        SysRegionEntity entity = sysRegionService.selectRegion(dto.getRegionid());
        if (StringUtils.isNotEmpty(entity)) {
            return new Result().error("区域标识已存在!");
        }
        String parentRegionId = dto.getParentRegionId();
        if (StringUtils.isNotEmpty(parentRegionId)) {
            entity = sysRegionService.selectRegion(parentRegionId);
            if (StringUtils.isEmpty(entity)) {
                return new Result().error("上级区域不存在!");
            }
            if (entity.getHashchildarea() != RegionHasChildareaEnum.YES.value()) {
                entity.setHashchildarea(RegionHasChildareaEnum.YES.value());
                SysRegionDTO regionsDTO = new SysRegionDTO();
                BeanUtils.copyProperties(entity, regionsDTO);
                sysRegionService.update(regionsDTO);//更新父节点
            }
            int parentRegionIdLength = parentRegionId.length();
            String regionId = dto.getRegionid().substring(0, parentRegionIdLength);
            if (!parentRegionId.equalsIgnoreCase(regionId)) {
                return new Result().error("区域标识必须以上级区域标识开头!");
            }
        }
        dto.setHashchildarea(RegionHasChildareaEnum.NO.value());
        sysRegionService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改保存地区区域信息")
    @LogOperation("修改保存地区区域信息")
    @RequiresPermissions("sys:region:update")
    public Result update(@RequestBody SysRegionDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        SysRegionDTO dtoDB = sysRegionService.get(dto.getId());
        if (dtoDB == null) {
            return new Result().error("该数据不存在!");
        }
        SysRegionEntity entity = sysRegionService.selectRegion(dto.getRegionid());
        if (StringUtils.isNotEmpty(entity)) {
            if (!dto.getId().equals(entity.getId())) {
                return new Result().error("区域标识已存在!");
            }
        }
        dtoDB.setRegionid(dto.getRegionid());// 区域标识(区划代码)
        dtoDB.setRegionseq(dto.getRegionseq());//区域排序
        dtoDB.setRegname(dto.getRegname());//区域名称(区划名称)
        sysRegionService.update(dtoDB);
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("根据主键删除地区区域信息")
    @LogOperation("根据主键删除地区区域信息")
    @RequiresPermissions("sys:region:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        for (Long id : ids) {
            SysRegionDTO dto = sysRegionService.get(id);
            if (dto == null) {
                return new Result().error("该数据不存在!");
            }
            List<SysRegionEntity> result = sysRegionService.getChildrenRegionid(dto.getRegionid());
            if (StringUtils.isNotEmpty(result) && result.size() > 0) {
                return new Result().error("该地区下有子级区域，不能删除!");
            }
        }
        sysRegionService.delete(ids);
        return new Result();
    }

    @GetMapping("list")
    @ApiOperation("获取区域列表或指定区域的子区域列表")
    @RequiresPermissions("sys:region:list")
    public Result<List<SysRegionDTO>> loadList(@RequestParam("regionid") String regionid, Integer firstInto, Integer root) {
        List<SysRegionDTO> list = sysRegionService.loadList(regionid, firstInto);
        return new Result<List<SysRegionDTO>>().ok(list);
    }

    @GetMapping("regionid")
    @ApiOperation("根据上级区域标识获取下级区域列表")
    public Result<List<SysRegionEntity>> getRegionsByRegionid(@RequestParam("regionid") String regionid, Integer firstInto, Integer root) {
        List<SysRegionEntity> data = null;
        if (StringUtils.isNotEmpty(root) && root == 1) {//此模式下如果超级管理员则从根节点查询
            data = sysRegionService.getRootRegionsByRegionid(regionid, firstInto);
        } else {
            data = sysRegionService.getRegionsByRegionid(regionid, firstInto);
        }
        return new Result<List<SysRegionEntity>>().ok(data);
    }

    @GetMapping("tree")
    @ApiOperation("树形数据")
    public Result<List<Map<String, Object>>> tree() {
        List<Map<String, Object>> list = sysRegionService.getTreeList();
        return new Result<List<Map<String, Object>>>().ok(list);
    }
}